package cn.signalpha.modules.resource.controller;

import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.utils.BeanUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.resource.dto.AttachCategoryDTO;
import cn.signalpha.modules.resource.entity.Attach;
import cn.signalpha.modules.resource.entity.AttachCategory;
import cn.signalpha.modules.resource.service.impl.AttachCategoryServiceImpl;
import cn.signalpha.modules.resource.service.impl.AttachServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 控制器
 *
 * @author signalpha
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SYSTEM_NAME + "/admin/attach/category")
@Api(value = "附件分类", tags = "附件分类")
public class AttachCategoryController extends BaseController {

	private final AttachServiceImpl attachService;
	private final AttachCategoryServiceImpl attachCategoryService;

    @PostMapping("/submit")
    @ApiOperation(value = "提交", notes = "传入attachCategory")
    public R submit(@Valid @RequestBody AttachCategoryDTO attachCategory) {
        return R.status(attachCategoryService.saveOrUpdate(BeanUtil.copy(attachCategory, AttachCategory.class)));
    }

	@PostMapping("/remove")
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		Func.toLongList(ids).forEach(id -> {
			AttachCategory attachCategory = attachCategoryService.getById(id);
			if(StringUtil.isNotBlank(attachCategory.getCode())){
				throw new ServiceException("内置分类不可删除");
			}
			if(attachService.count(Wrappers.<Attach>lambdaQuery().eq(Attach::getCategoryId, id)) > 0){
				throw new ServiceException("请先删除分类下的附件");
			}
			attachCategoryService.removeById(id);
		});
		return R.status(true);
	}

}
